<template>
  <div class="container">
    <div class="card-container">
      <el-card v-for="room in getroomlist" :key="room.id" class="room-card" style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <span>{{ room.roomname }}</span>
          </div>
        </template>
        <div class="card-body">
          <p>负责人：{{ room.username }}</p>
          <p>容纳人数: {{ room.capacity }}</p>
          <p>位置：{{ room.location }}</p>
          <p>负责人电话：{{ room.phone }}</p>
        </div>
      </el-card>
    </div>

    <FullCalendar
        v-if="fullCalendarInitialized"
        ref="fullCalendar"
        :options="calendarOptions"
        class="fullcalendar"

    />

    <el-dialog v-model="dialogVisible" title="预定详情" width="600" center :append-to-body="true" class="custom-dialog">
      <div v-if="selectedBooking" class="dialog-content">
        <span><strong>房间名称：</strong> {{ selectedBooking.title }}</span>
        <p><strong>开始时间：</strong> {{ selectedBooking.start }}</p>
        <p><strong>结束时间：</strong> {{ selectedBooking.end }}</p>
        <p><strong>活动名称：</strong> {{ selectedBooking.reason }}</p>
        <p><strong>描述：</strong> {{ selectedBooking.description }}</p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import FullCalendar from '@fullcalendar/vue3';
import resourceTimelinePlugin from '@fullcalendar/resource-timeline';
import { ref, onMounted, computed, nextTick } from 'vue';
import { roomlist } from "@/api/room";
import { roomBookUsage } from "@/api/book";
const roomdata = ref([]);
const getroomlist = ref([]);
const statlist = ref([]);
const eventList = ref([]);
const selectedDate = ref(new Date());
const fullCalendarRef = ref(null);
const fullCalendarInitialized = ref(false);
const dialogVisible = ref(false); // 控制对话框显示
const selectedBooking = ref(null); // 选择的预定信息

const calendarOptions = ref({
  plugins: [resourceTimelinePlugin],
  initialView: 'resourceTimeline',
  resources: computed(() => statlist.value),
  events: computed(() => eventList.value),
  locale: 'zh-cn',
  // display:'block',
  eventColor: 'rgb(255 223 193)',
  eventTextColor:"rgb(255, 162, 77)",
  // eventBorderColor:"rgb(221, 243, 245)",
  aspectRatio: 1.65,
  // eventLimit: true,
  height: 'auto',
  headerToolbar:
      {
        left: 'prev,next today',
        center: 'title',
        right: '',
      },
  resourceAreaWidth: '15%',// 高级功能配置Column宽度
  expandRows: true,
  businessHours: [
    {
      daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
      startTime: '9:00', // 可接受字符串或处理函数
      endTime: '24:00'
    }
  ],
  // nowIndicator: true, // 是否显示时间指示器
  resourceAreaColumns: [
    // {
    //   group: true,
    //   field: 'building',
    //   headerContent: '',
    //   width: '60%'
    // },
    {
      filed: 'occupancy',
      headerContent: '',
      // height:'12%',
      // width:'1%',
      cellClassNames: 'fullCalendarCell',
      eventLimit:false
    }
  ],
  eventSources:[{
    display:'block',
    color: 'rgb(221, 243, 245)',
    backgroundColor: 'rgb(255 223 193)',
    textColor: 'rgb(255, 162, 77)'
  }],
  // footerToolBar:false,
  handleWindowResize: true,
  timeZone: 'local',
  eventClick: handleEventClick,
  initialDate: new Date(),
  // timeZone: 'UTC',
  slotMinTime: '09:00:00', // 开始时间
  // soltEventOverlap:false,
  slotMaxTime: '18:00:00', // 结束时间
});

onMounted(async () => {
  await fetchRoomData();
  fullCalendarInitialized.value = true;
  await nextTick();
});

async function fetchRoomData() {
  try {
    const roomResponse = await roomlist();
    getroomlist.value = roomResponse.data;

    const response = await roomBookUsage();
    await updateRoomData(response.data);
    roomdata.value = response.data;
    // console.log('222222222222222222')
    console.log(response.data)
    // console.log("1111111111111")
    await updateEventList();
  } catch (error) {
    console.error("Error fetching room data:", error);
    alert("无法加载房间数据，请稍后再试。");
  }
}

function updateRoomData(data) {
  const roomMap = {};

  data.forEach(item => {
    if (!roomMap[item.roomname]) {
      roomMap[item.roomname] = [];
    }
    roomMap[item.roomname].push({
      startTime: item.startTime,
      endTime: item.endTime,
      description: item.description,
      reason:item.reason,
      id:item.id
    });
  });

  statlist.value = Object.keys(roomMap).map((roomName, index) => ({
    id: index.toString(),
    title: roomName,
    bookings: roomMap[roomName]
  }));
}

async function updateEventList() {
  const bookings = statlist.value.flatMap(room =>
      room.bookings.map(booking => ({
        resourceId: room.id,
        start: booking.startTime,
        end: booking.endTime,
        title: room.title,
        description: booking.description,
        reason:booking.reason,
        id : booking.id
      }))
  );

  console.log("22:",bookings)
  eventList.value = bookings;
}
function handleEventClick(arg) {
  // console.log(eventList.value);
console.log(1111)

  console.log(arg.event.id)
  console.log(eventList.value)
  console.log(arg.event)
  const eventTitle = arg.event.title;

const eventId = arg.event.id;
// const eventEnd = arg.event.end;
// &&b.id===eventId
// && b.start === eventStart&&b.end === eventEnd
console.log(2222)
  const booking = eventList.value.find(b => b.title === eventTitle&&b.id==eventId );

  console.log(booking);
  if (booking) {
    selectedBooking.value = booking;
    console.log("Opening dialog with booking:", selectedBooking.value);
    dialogVisible.value = true; // 打开对话框
    console.log("Dialog visible state set to:", dialogVisible.value);

    // 调试输出，确保函数执行到了这里
    setTimeout(() => {
      console.log("After setting dialogVisible to true:", dialogVisible.value);
    }, 0);
  } else {
    alert(`Event clicked: ${eventTitle} (No additional info found)`);
  }
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 100vh;
}

.card-container {
  width: 300px;
  padding: 20px;
  border-right: 1px solid #ddd;
  overflow-y: auto;
}

.room-card {
  width: 100%;
}

.fullcalendar {
  flex: 1;
  margin: 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/*增加日历头部工具栏样式*/
.fc-toolbar {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f5f5; /* 背景颜色 */
  border-bottom: 1px solid #ddd; /* 底部边框 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.fc-toolbar .fc-button {
  padding: 5px 10px;
}

/*自定义事件的样式*/
.fc-event {
  background-color: #3BB2E3;  /* 默认事件背景颜色 */
  border: none; /* 去掉边框 */
  color: white; /* 字体颜色 */
  border-radius: 5px; /* 圆角 */
}

/*dialog 样式*/
.custom-dialog {
  font-size: 20px; /* 调整整体字体大小 */
}

.dialog-content {
  font-size: 18px;  /* 内容字体大小 */
}

.dialog-content strong {
  font-size: 18px;  /* 加粗文本字体大小 */
  color: #333;      /* 改变颜色 */
}

.dialog-content p {
  margin: 4px 0;  /* 段落间距 */
}
::v-deep .fc-timeline-event {
  margin-right: 0;
}
.fc-row{
  height: 50px !important;
}

.fc-event {
  min-height: initial;
  background-color: transparent; /*透明背景 */
  border: none; /* 去掉边框 */
  color: white; /* 字体颜色 */
  border-radius: 5px; /* 圆角 */
}

.fc-event.overlap {
  background-color: rgba(255, 165, 0, 0.8); /* 重叠事件的背景颜色 */
}


</style>